package com.ffapp.demo.map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;
import com.ffapp.demo.view.SizeChangeRelativeLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.DisplayUtil;
import my.LogUtil;
import my.ViewUtils;

public class MapWechatAddressChoose extends BasisActivity implements LocationSource,
        AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener, PoiSearch.OnPoiSearchListener { // Inputtips.InputtipsListener

    public static void toMapAddressChoose(Activity activity, String title, int request_code) {
        Bundle extras = new Bundle();
        extras.putString("title", title);
        ActivityTool.skipActivityForResult(activity, MapWechatAddressChoose.class, extras, request_code);
    }

    public static void toMapAddressChoose(Fragment fragment, String title, int request_code) {
        Bundle extras = new Bundle();
        extras.putString("title", title);
        Intent initent = new Intent(fragment.getContext(), MapWechatAddressChoose.class);
        fragment.startActivityForResult(initent, request_code, extras);
//        ActivityTool.skipActivityForResult(activity,MapAddressChoose.class,extras,request_code);
    }


    @BindView(R.id.recyclerview)
    RecyclerView listView;

    private AMap aMap;
    @BindView(R.id.map)
    MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private Marker locationMarker;

    private ProgressDialog progDialog = null;
    private GeocodeSearch geocoderSearch;

    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private List<PoiItem> poiItems;// poi数据

    private String searchKey = "";
    private LatLonPoint searchLatlonPoint;


    private List<PoiItem> resultData;

    private SearchResultAdapter searchResultAdapter;

    private boolean isItemClickAction;

    private List<Tip> autoTips;
    private boolean isfirstinput = true;
    private PoiItem firstItem;

    String cityname = "";


    @BindView(R.id.coordinatorlayout)
    CoordinatorLayout coordinatorlayout;
    @BindView(R.id.bottom_sheet)
    View bottomSheet;
    private BottomSheetBehavior behavior;
    int bottomStatus = BottomSheetBehavior.STATE_COLLAPSED;


    @BindView(R.id.edit_search)
    EditText edit_search;

    boolean isSearchMode = false;
    @BindView(R.id.view_search_edit_zone)
    View view_search_edit_zone;
    @BindView(R.id.view_search_hint_zone)
    View view_search_hint_zone;
    @BindView(R.id.text_cancel)
    TextView text_cancel;
    @BindView(R.id.recyclerview_search)
    RecyclerView recyclerview_search;
    @BindView(R.id.view_relatevelayout)
    SizeChangeRelativeLayout view_relatevelayout;
    private SearchResultAdapter searchResultAdapter_search;

    @Override
    public void initViews() {
        super.initViews();
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.map_wechat_address_choose_activity);
        setTitle("地图选址");
        setTitleLeftButton(null);

        listView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerview_search.setLayoutManager(new LinearLayoutManager(mContext));


        behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, @BottomSheetBehavior.State int newState) {
                if (newState == BottomSheetBehavior.STATE_EXPANDED) {
//                    tvGoldDownMore.setVisibility(View.GONE);
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams();
                    layoutParams.setMargins(0, -120, 0, layoutParams.bottomMargin);
                    mapView.setLayoutParams(layoutParams);
                    if(edit_search.isFocused()){
                        ViewUtils.showInput(mContext,edit_search);
                    }

                } else if (newState == BottomSheetBehavior.STATE_DRAGGING) {
//                    tvGoldDownMore.setVisibility(View.VISIBLE);
                } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams();
                    layoutParams.setMargins(0, DisplayUtil.dip2px(mContext, 50) + QMUIStatusBarHelper.getStatusbarHeight(mContext), 0, layoutParams.bottomMargin);
                    mapView.setLayoutParams(layoutParams);

                    ViewUtils.hideInput(mContext, edit_search);
                }
                bottomStatus = newState;
                Log.d("MainActivity", "newState:" + newState);
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });

        edit_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        String title = getIntent().getStringExtra("title");
        if (!TextUtils.isEmpty(title)) {
            setTitle(title);
        }


        if (mapView == null)
            mapView = (MapView) findViewById(R.id.map);


        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mapView.getLayoutParams();
        layoutParams.setMargins(0, DisplayUtil.dip2px(mContext, 50) + QMUIStatusBarHelper.getStatusbarHeight(mContext), 0, layoutParams.bottomMargin);
        mapView.setLayoutParams(layoutParams);

        mapView.onCreate(savedInstanceState);


        init();
        initView();
        resultData = new ArrayList<>();
        setTitleRightText("确认", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PoiItem item = null;
                if (isSearchMode) {
                    if (searchResultAdapter_search == null || searchResultAdapter_search.getItemCount() == 0) {
                        return;
                    }
                    item = searchResultAdapter_search.getSeletedItem();


                } else {
                    if (searchResultAdapter == null || searchResultAdapter.getItemCount() == 0) {
                        return;
                    }
                    item = searchResultAdapter.getSeletedItem();

//                    if(searchResultAdapter.getSelectedPosition() != 0){
////                    firstItem =  new PoiItem("regeo", searchLatlonPoint, AMapUtil.getAddressNameFromPoiItem(item),  item.getSnippet());
////                    firstItem =  new PoiItem("regeo", searchLatlonPoint, item.getProvinceName()+item.getCityName() + item.getAdName() + item.getSnippet(),  item.getSnippet());
//                        firstItem =  new PoiItem("regeo", searchLatlonPoint, item.getTitle(),  item.getSnippet());
//                        firstItem.setProvinceName(item.getProvinceName() );
//                        firstItem.setCityName(item.getCityName() );
//                        firstItem.setAdName(item.getAdName());
//                    }

                }

                if (item == null) {
                    showToast("未选择地址");
                    return;
                }

                if (item != null) {
                    firstItem = new PoiItem("regeo", searchLatlonPoint, item.getTitle(), item.getSnippet());
                    firstItem.setProvinceName(item.getProvinceName());
                    firstItem.setCityName(item.getCityName());
                    firstItem.setAdName(item.getAdName());
                }

                Intent intentResult = new Intent();
                intentResult.putExtra("data", firstItem);
                setResult(Activity.RESULT_OK, intentResult);
                finish();
            }
        });
    }


    private void initView() {

        searchResultAdapter = new SearchResultAdapter(MapWechatAddressChoose.this, new SearchResultAdapter.OnAddressClickListener() {
            @Override
            public void onAddressClick(int position) {
                if (position != searchResultAdapter.getSelectedPosition()) {
                    PoiItem poiItem = (PoiItem) searchResultAdapter.getItem(position);
                    LatLng curLatlng = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
                    isItemClickAction = true;
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
                    searchResultAdapter.setSelectedPosition(position);
                    searchResultAdapter.notifyDataSetChanged();
                }
            }
        });
        listView.setAdapter(searchResultAdapter);

        searchResultAdapter_search = new SearchResultAdapter(MapWechatAddressChoose.this, new SearchResultAdapter.OnAddressClickListener() {
            @Override
            public void onAddressClick(int position) {
                if (position != searchResultAdapter_search.getSelectedPosition()) {
                    PoiItem poiItem = (PoiItem) searchResultAdapter_search.getItem(position);
                    LatLng curLatlng = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
                    isItemClickAction = true;
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
                    searchResultAdapter_search.setSelectedPosition(position);
                    searchResultAdapter_search.notifyDataSetChanged();

                    behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }
        });
        recyclerview_search.setAdapter(searchResultAdapter_search);

//        listView.setOnItemClickListener(onItemClickListener);

        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch();
            }
        });

//        edit_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Log.i("MY", "setOnItemClickListener");
//                if (autoTips != null && autoTips.size() > position) {
//                    Tip tip = autoTips.get(position);
//                    searchPoi(tip);
//                }
//            }
//        });

        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        progDialog = new ProgressDialog(this, R.style.loading_dialog);

        hideSoftKey(edit_search);

        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_SEARCH) {
                    doSearch();
                    return true;
                }
                return false;
            }
        });


    }

    void setSearchModeView() {
        searchResultAdapter_search.setData(null);
        searchResultAdapter_search.setSelectedPosition(-1);
        searchResultAdapter_search.notifyDataSetChanged();

        if (isSearchMode) {
            view_search_edit_zone.setVisibility(View.VISIBLE);
            view_search_hint_zone.setVisibility(View.INVISIBLE);
            text_cancel.setVisibility(View.VISIBLE);
            ViewUtils.showInput(mContext, edit_search);


            recyclerview_search.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        } else {
            view_search_edit_zone.setVisibility(View.INVISIBLE);
            view_search_hint_zone.setVisibility(View.VISIBLE);

            text_cancel.setVisibility(View.GONE);

            ViewUtils.hideInput(mContext, edit_search);
            recyclerview_search.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);

            if (searchResultAdapter_search != null) {
                searchResultAdapter_search.setData(null);
                searchResultAdapter_search.setSelectedPosition(-1);
                searchResultAdapter_search.notifyDataSetChanged();
                edit_search.setText("");
            }
            if (searchResultAdapter != null && searchResultAdapter.getItemCount() > 0 && searchResultAdapter.getSelectedPosition() >= 0) {
                int seletePosition = searchResultAdapter.getSelectedPosition();
                PoiItem poiItem = (PoiItem) searchResultAdapter.getItem(seletePosition);
                LatLng curLatlng = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());
                isItemClickAction = true;
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
            }
        }
    }

    @OnClick(R.id.view_search_hint_zone)
    void onSearchHintClick() {
        isSearchMode = true;
        setSearchModeView();
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }

    @OnClick(R.id.text_cancel)
    void onSearchCancelClick() {
        isSearchMode = false;
        setSearchModeView();
        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
    }

    void doSearch() {
        String searchKeyWords = edit_search.getText().toString();
        if (TextUtils.isEmpty(searchKeyWords)) {
            searchResultAdapter_search.setSelectedPosition(-1);
            searchResultAdapter_search.setData(null);
            searchResultAdapter_search.notifyDataSetChanged();
        } else {

//            showLoading();
            InputtipsQuery inputquery = new InputtipsQuery(searchKeyWords, cityname);
            Inputtips inputTips = new Inputtips(MapWechatAddressChoose.this, inputquery);
            inputquery.setCityLimit(true);
            inputTips.setInputtipsListener(inputtipsListener);
            inputTips.requestInputtipsAsyn();
        }
    }

    /**
     * 初始化
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

        aMap.setOnCameraChangeListener(onCameraChangeListener);

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkerInScreenCenter(null);
            }
        });
    }

    AMap.OnCameraChangeListener onCameraChangeListener = new AMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            searchLatlonPoint = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
            if (!isItemClickAction && !isInputKeySearch) {
                geoAddress();
                startJumpAnimation();
//                if(isSearchMode){
//                    isSearchMode = false;
//                    searchResultAdapter.setSelectedPosition(-1);
//                    setSearchModeView();
//                }
            }
            isInputKeySearch = false;
            isItemClickAction = false;

        }
    };

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
//        Log.i("MY", "onLocationChanged");
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);

                if (searchResultAdapter != null) {
                    searchResultAdapter.setDataLocation(amapLocation);
                }
                if (searchResultAdapter_search != null) {
                    searchResultAdapter_search.setDataLocation(amapLocation);
                }

                LatLng curLatlng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                searchLatlonPoint = new LatLonPoint(curLatlng.latitude, curLatlng.longitude);
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));


                isInputKeySearch = false;

//                searchText.setText("");
                if (!TextUtils.isEmpty(amapLocation.getProvince())) {
                    cityname = amapLocation.getCity();
                }
                LogUtil.i("onLocationChanged----->" + cityname);
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    /**
     * 响应逆地理编码
     */
    public void geoAddress() {
//        Log.i("MY", "geoAddress"+ searchLatlonPoint.toString());
        showDialog();
//        searchText.setText("");
        if (searchLatlonPoint != null) {
            RegeocodeQuery query = new RegeocodeQuery(searchLatlonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            geocoderSearch.getFromLocationAsyn(query);
        }
    }

    /**
     * 开始进行poi搜索
     */
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
//        Log.i("MY", "doSearchQuery");
        currentPage = 0;
//        query = new PoiSearch.Query(searchKey, searchType, "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(searchKey, "", "");
        query.setCityLimit(true);
        query.setPageSize(20);
        query.setPageNum(currentPage);

        if (searchLatlonPoint != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(searchLatlonPoint, 1000, true));//
            poiSearch.searchPOIAsyn();
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        dismissDialog();
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                String address = result.getRegeocodeAddress().getProvince() + result.getRegeocodeAddress().getCity() + result.getRegeocodeAddress().getDistrict() + result.getRegeocodeAddress().getTownship();
                firstItem = new PoiItem("regeo", searchLatlonPoint, address, result.getRegeocodeAddress().getTownship());
                firstItem.setProvinceName(result.getRegeocodeAddress().getProvince());
                firstItem.setCityName(result.getRegeocodeAddress().getCity());
                firstItem.setAdName(result.getRegeocodeAddress().getDistrict());

                doSearchQuery();
            }
        } else {
//            Toast.makeText(MapAddressChoose.this, "error code is " + rCode, Toast.LENGTH_SHORT).show();
            showToast("发生错误，请稍后再试");
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    /**
     * POI搜索结果回调
     *
     * @param poiResult  搜索结果
     * @param resultCode 错误码
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int resultCode) {
        if (resultCode == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {
                if (poiResult.getQuery().equals(query)) {
                    poiItems = poiResult.getPois();
                    if (poiItems != null && poiItems.size() > 0) {
                        updateListview(poiItems);   //地图移动
                    } else {
                        Toast.makeText(MapWechatAddressChoose.this, "无搜索结果", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(MapWechatAddressChoose.this, "无搜索结果", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 更新列表中的item
     *
     * @param poiItems
     */
    private void updateListview(List<PoiItem> poiItems) {
        if(isSearchMode){
            isSearchMode = false;
            view_search_edit_zone.setVisibility(View.INVISIBLE);
            view_search_hint_zone.setVisibility(View.VISIBLE);

            text_cancel.setVisibility(View.GONE);

            ViewUtils.hideInput(mContext, edit_search);
            recyclerview_search.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);

            if (searchResultAdapter_search != null) {
                searchResultAdapter_search.setData(null);
                searchResultAdapter_search.setSelectedPosition(-1);
                searchResultAdapter_search.notifyDataSetChanged();
                edit_search.setText("");
            }
        }
        resultData.clear();
        searchResultAdapter.setSelectedPosition(0);
//        resultData.add(firstItem);
        resultData.addAll(poiItems);

        searchResultAdapter.setData(resultData);
        searchResultAdapter.notifyDataSetChanged();


    }


    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position != searchResultAdapter.getSelectedPosition()) {
                PoiItem poiItem = (PoiItem) searchResultAdapter.getItem(position);
                LatLng curLatlng = new LatLng(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude());

                isItemClickAction = true;
                aMap.setOnCameraChangeListener(null);
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
                aMap.setOnCameraChangeListener(onCameraChangeListener);
                searchResultAdapter.setSelectedPosition(position);
                searchResultAdapter.notifyDataSetChanged();
            }
        }
    };

    public void showDialog() {
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在加载...");
        progDialog.show();
    }

    public void dismissDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    private void addMarkerInScreenCenter(LatLng locationLatLng) {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        locationMarker = aMap.addMarker(new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_icon_purple_pin)));
        //设置Marker在屏幕上,不跟随地图移动
        locationMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        locationMarker.setZIndex(1);

    }

    /**
     * 屏幕中心marker 跳动
     */
    public void startJumpAnimation() {

        if (locationMarker != null) {
            //根据屏幕距离计算需要移动的目标点
            final LatLng latLng = locationMarker.getPosition();
            Point point = aMap.getProjection().toScreenLocation(latLng);
            point.y -= dip2px(this, 125);
            LatLng target = aMap.getProjection()
                    .fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if (input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f) * (1.5f - input)));
                    }
                }
            });
            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            locationMarker.setAnimation(animation);
            //开始动画
            locationMarker.startAnimation();

        } else {
            Log.e("ama", "screenMarker is null");
        }
    }

    //dip和px转换
    private static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    Inputtips.InputtipsListener inputtipsListener = new Inputtips.InputtipsListener() {
        @Override
        public void onGetInputtips(List<Tip> list, int rCode) {
            hideLoading();
            if (rCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
                autoTips = list;
//                List<String> listString = new ArrayList<String>();
//                for (int i = 0; i < list.size(); i++) {
//                    listString.add(list.get(i).getName());
//                }
//                LogUtil.i("onGetInputtips------0--->"+autoTips.get(0).toString());
//                ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
//                        getApplicationContext(),
//                        R.layout.map_route_inputs, listString);
//                searchText.setAdapter(aAdapter);
//                aAdapter.notifyDataSetChanged();
                if (autoTips == null || autoTips.size() == 0) {
                    searchResultAdapter_search.setData(null);
                    searchResultAdapter_search.setSelectedPosition(0);
                    searchResultAdapter_search.notifyDataSetChanged();
                } else {
                    ArrayList<PoiItem> listPoi = new ArrayList<>();

                    for (int i = 0, l = autoTips.size(); i < l; i++) {
                        Tip tip = autoTips.get(i);
                        PoiItem poiItem = new PoiItem("tip" + i, tip.getPoint(), tip.getName(), "");
                        LogUtil.i("tip.getAddress()--->" + tip.getAddress());
                        LogUtil.i("tip.getAddress()--->" + tip.toString());
                        if(TextUtils.isEmpty(tip.getAddress())){
                            poiItem.setAdName(tip.getDistrict());
                        }else {
                            poiItem.setAdName(tip.getAddress());
                        }
                        listPoi.add(poiItem);
                    }
                    searchResultAdapter_search.setData(listPoi);
                    searchResultAdapter_search.setSelectedPosition(-1);
                    searchResultAdapter_search.notifyDataSetChanged();
                }
            } else {
                Toast.makeText(MapWechatAddressChoose.this, "erroCode " + rCode, Toast.LENGTH_SHORT).show();
            }
        }
    };

    private boolean isInputKeySearch;
    private String inputSearchKey;

    private void searchPoi(Tip result) {
        isInputKeySearch = true;
        inputSearchKey = result.getName();//getAddress(); // + result.getRegeocodeAddress().getCity() + result.getRegeocodeAddress().getDistrict() + result.getRegeocodeAddress().getTownship();
        searchLatlonPoint = result.getPoint();
        firstItem = new PoiItem("tip", searchLatlonPoint, inputSearchKey, result.getAddress());
        firstItem.setCityName(result.getDistrict());
        firstItem.setAdName("");

        resultData.clear();

        searchResultAdapter.setSelectedPosition(0);

        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(searchLatlonPoint.getLatitude(), searchLatlonPoint.getLongitude()), 16f));

        hideSoftKey(edit_search);
        doSearchQuery();
    }

    private void hideSoftKey(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    boolean isSetBottomSheetHeight = false;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        //修改SetBottomSheet的高度 留出顶部工具栏的位置
        if (!isSetBottomSheetHeight) {
            CoordinatorLayout.LayoutParams linearParams = (CoordinatorLayout.LayoutParams) bottomSheet.getLayoutParams();
            linearParams.height = coordinatorlayout.getHeight() - DisplayUtil.dip2px(mContext, 200);
//            fraBottomSheetHeight = linearParams.height;
            bottomSheet.setLayoutParams(linearParams);
            isSetBottomSheetHeight = true;

        }

        LogUtil.i("onWindowFocusChanged-------->" + isSetBottomSheetHeight);
    }



    void toggle() {
        if (bottomStatus != BottomSheetBehavior.STATE_EXPANDED) {
            behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        } else {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    }
}
